package cn.youruan.demo.controller;

import cn.youruan.demo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${file.imgPath}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("开始进行文件上传...");
        //获取原始文件名(也就是上传时的名字)
        String originalFilename = file.getOriginalFilename();
        //使用UUID防止生成唯一文件名,防止文件名重复覆盖
        String s = UUID.randomUUID().toString();
        //拿.jpg后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接文件名
        String fileName = s+suffix;
        //创建一个目录对象
        // 为了防止电脑不存在目录比如H:\\test\1.txt没有test这个文件夹
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在需要创建
            dir.mkdirs();
        }
        try {
            //将文件保存到指定目录
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件上传失败!!!");
        }
        log.info("文件上传成功!!!");
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     * @return
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        //1.过输入流读取文件内容
        try {
            FileInputStream inputStream = new FileInputStream(new File(basePath+name));
            //2.通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length=inputStream.read(bytes)) != -1) {
                //从第一个开始读,读取length这么长
                outputStream.write(bytes,0,length);
                outputStream.flush();
                //关闭资源
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
